import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-11-18
 * Time: 19:20
 */
public class UdpEchoServer {
    //接收数据报
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        //服务器指定一个固定端口
        socket = new DatagramSocket(port);
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动");
        //客户端发送很多请求
        while(true) {
            //每循环一次相当于一次请求
            //处理请求步骤
            //1.接受请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[5096],5096);
            //接受客户端发来的请求,放到requestPacket里面
            socket.receive(requestPacket);
            //将请求中的二进制数据解析成字符串
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());

            //2.根据请求，计算响应
            String response = process(request);

            //3.将请求发送给客户端
            //将响应构造成数据报
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),0,
                    response.getBytes().length,requestPacket.getSocketAddress());
            //发送响应
            socket.send(responsePacket);

            //4.打印一个日志
            System.out.printf("[%s:%d]--request: %s, response: %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }
    //实现中英翻译
    private String process(String request) {
        HashMap<String,String> dict = new HashMap<>();
        //初始化字典
        dict.put("小猫", "cat");
        dict.put("小狗", "dog");
        dict.put("小兔子", "rabbit");
        dict.put("小鸭子", "duck");

        return dict.getOrDefault(request,"未找到该翻译");
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
